package com.xxw.springbootencrypt.config;

import com.xxw.springbootencrypt.util.RsaUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;

@Component
@Data
public class RsaConfig {
	@Value("${keysUrl.pubKeyFileUrl}")
	private String pubKeyFileUrl;
	@Value("${keysUrl.priKeyFileUrl}")
	private String priKeyFileUrl;
	@Value("${keysUrl.secret}")
	private String secret;

	/*
	* Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
	* */
	@PostConstruct //构造方法以后执行
	private void init(){
		File pubfile=new File(this.getPubKeyFileUrl());//创建公钥的文件类
		File prifile=new File(this.getPriKeyFileUrl());//创建私钥的文件类

		//公钥或者私钥不存在，新建一套
		if (!pubfile.exists() || !prifile.exists())
		{
			try {
				RsaUtil.generateKey(this.getPubKeyFileUrl(), this.getPriKeyFileUrl(), this.getSecret());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

